#include "drv_gpio.h"
/* HC32 GPIO driver */
const struct pin_index *get_pin(uint8_t pin)
{
    const struct pin_index *index;

    if (pin < ITEM_NUM(pins))
    {
        index = &pins[pin];
        if (index->index == -1)
            index = RT_NULL;
    }
    else
    {
        index = RT_NULL;
    }

    return index;
};
void drv_hc32_pin_mode(uint8_t pin, uint32_t mode)//(rt_device_t dev, rt_base_t pin, rt_base_t mode)
{
    const struct pin_index *index;
    stc_gpio_init_t stcGpioInit;
    index = get_pin(pin);
    if (index == RT_NULL)
    {
        return;
    }
	GPIO_StructInit(&stcGpioInit);
    if (mode == PIN_MODE_OUTPUT)
    {
        /* output setting */
        stcGpioInit.u16PinDir = PIN_DIR_OUT;
        stcGpioInit.u16PinOType = PIN_OTYPE_CMOS;//Push-Pull
        stcGpioInit.u16PullUp = PIN_PU_OFF;
//        stcGpioInit.u16PinIType = PIN_ITYPE_SMT;//Schmidt
    }
    else if (mode == PIN_MODE_INPUT)
    {
        /* input setting: not pull. */
        stcGpioInit.u16PinDir = PIN_DIR_IN;
        stcGpioInit.u16PinOType = PIN_OTYPE_CMOS;//Push-Pull
        stcGpioInit.u16PullUp = PIN_PU_OFF;
//        stcGpioInit.u16PinIType = PIN_ITYPE_SMT;//Schmidt
    }
    else if (mode == PIN_MODE_INPUT_PULLUP)
    {
        /* input setting: pull up. */
        stcGpioInit.u16PinDir = PIN_DIR_IN;
        stcGpioInit.u16PinOType = PIN_OTYPE_CMOS;//Push-Pull
        stcGpioInit.u16PullUp = PIN_PU_ON;
//        stcGpioInit.u16PinIType = PIN_ITYPE_SMT;//Schmidt
    }
    else if (mode == PIN_MODE_INPUT_PULLDOWN)
    {
        return;//no pull down
        /* input setting: pull down. */
    }
    else if (mode == PIN_MODE_OUTPUT_OD)
    {
        /* output setting: od. */
        stcGpioInit.u16PinDir = PIN_DIR_IN;
        stcGpioInit.u16PinOType = PIN_OTYPE_NMOS;//Push-Pull
        stcGpioInit.u16PullUp = PIN_PU_OFF;
    }
	GPIO_Unlock();
	GPIO_Init(index->gpio, index->pin, &stcGpioInit);
	GPIO_Lock();
}
void drv_hc32_pin_write(uint8_t pin, uint8_t value)//(rt_device_t dev, rt_base_t pin, rt_base_t value)
{
    const struct pin_index *index;
    index = get_pin(pin);
    if (index == RT_NULL)
    {
        return;
    }
    if((bool)value == 1)
    {
        GPIO_SetPins(index->gpio, index->pin);
    }
    else
    {
        GPIO_ResetPins(index->gpio, index->pin);
    }
}
int drv_hc32_pin_read(uint8_t pin)//(rt_device_t dev, rt_base_t pin)
{
    int value;
    const struct pin_index *index;

    value = 0;

    index = get_pin(pin);
    if (index == RT_NULL)
    {
        return value;
    }

    value = GPIO_ReadInputPins(index->gpio, index->pin);

    return value;
}
void drv_hc32_pin_func_set(uint8_t pin, uint8_t func)
{
    const struct pin_index *index;
    index = get_pin(pin);
    if (index == RT_NULL)
    {
        return;
    }
    GPIO_Unlock();
	GPIO_SetFunc(index->gpio, index->pin, func, Disable);
	GPIO_Lock();
}